package com.freecloud.tomcat.bio.http;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

/**
 * @Author: maomao
 * @Date: 2021/8/30 10:04 上午
 */
public class FreeResponse {

    private ChannelHandlerContext ctx;
    private HttpRequest req;

    public FreeResponse(ChannelHandlerContext ctx, HttpRequest req) {
        this.ctx = ctx;
        this.req = req;
    }

    public void write(String s) throws Exception {
        if (s == null || s.length() == 0) {
            return;
        }
        try {

            FullHttpResponse response = new DefaultFullHttpResponse(
                //设置Http版本号为1.1
                HttpVersion.HTTP_1_1,
                //设置状态码为200
                HttpResponseStatus.OK,
                //统一输出格式为utf-8
                Unpooled.wrappedBuffer(s.getBytes(StandardCharsets.UTF_8)));
            response.headers().set("Content-type", "text/html;charset=UTF-8");
            ctx.write(response);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ctx.flush();
            ctx.close();
        }
    }
}
